import { defineStore } from 'pinia'
import request from '@/utils/request.js'

export const useBlogsStore = defineStore("blogs", {
  state: () => {
    return {
      blogs: [], // 所有的数据
      blogPage: {}, // 分页的数据
      hotBlogs: [] // 热门数据
    };
  },
  getters: {
    sorted: (state) => {
      return state.blogPage.list.sort((a, b) => new Date(b.date) - new Date(a.date));
    },
    sortedAll: (state) => {
      return state.blogs.list.sort((a, b) => new Date(b.date) - new Date(a.date));
    },
  },
  actions: {
    async getArticleList() { // 废弃
      try {
        let res = await request.get('/article/list')
        this.blogs = res.data.data;
        return res.data.data;
      } catch (error) {
        console.error(error);
      }
    },
    async articlePages(currentPage, size) {
      try {
        let params = {
          currentPage,
          size
        }
        let res = await request.post('/article/pages', params)
        this.blogPage = res.data.data;
        return res.data.data;
      } catch (error) {
        console.error(error);
      }
    },
    async getHotBlogs() {
      try {
        let res = await request.get('/article/hots')
        this.hotBlogs = res.data.data.list;
        return res.data.data;
      } catch (error) {
        console.error(error);
      }
    },
    addBlog(blog) {
      const addblog = {
        id: this.blogs.length + 1,
        title: blog.title,
        author: "枫叶🍁",
        date: new Date().toISOString().split("T")[0],
        content: blog.content,
      };
      this.blogs.push(addblog);
    },
    async getBlogById(id) {
      try {
        let res = await request.post('/article/detail', {id: id});
        return res.data.data;
      } catch (error) {
        console.error(error);
      }
    },
  },
});
